package TestDemo;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class TestDemo8 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的路径");
        String rootPath = scanner.next();
        File root = new File(rootPath);
        if (!root.exists()) {
            System.out.println("您输入的路径不存在");
            return;
        }
        System.out.println("请输入你需要删除的文件名(或者一部分)");
        String toDelete = scanner.next();

        scanDir(root, toDelete);
    }

    public static void scanDir(File rootDir, String toDelete) {
        File[] files = rootDir.listFiles();
        if (files == null) {
            return;
        }
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                scanDir(files[i], toDelete);
            } else {
                tryDelete(files[i], toDelete);
            }
        }
    }

    public static void tryDelete(File f, String toDelete) {
        if (f.getName().contains(toDelete)) {
            try {
                System.out.println("是否要删除文件(Y/N): " + f.getCanonicalPath());
                Scanner scanner = new Scanner(System.in);
                String choice = scanner.next();
                if (choice.equals("Y")) {
                    f.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
